package com.narata.netty.handler;

import com.narata.netty.message.LoginRequestMessage;
import com.narata.netty.message.LoginResponseMessage;
import com.narata.netty.service.UserServiceFactory;
import com.narata.netty.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 22:47 2022-05-29
 * @Modified By:
 **/
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {

        String password = msg.getPassword();
        String username = msg.getUsername();
        LoginResponseMessage loginResponseMessage;
        boolean login = UserServiceFactory.getUserService().login(username, password);
        if (login) {
            SessionFactory.getSession().bind(ctx.channel(), username);
            loginResponseMessage = new LoginResponseMessage(true, "登陆成功");
        } else {

            loginResponseMessage = new LoginResponseMessage(false, "登陆失败，用户名或密码错误!");
        }
        ctx.writeAndFlush(loginResponseMessage);
    }
}
